#include "LayerPropertiesDialog.h"

LayerPropertiesDialog::LayerPropertiesDialog(QListWidgetItem * item, QAbstractItemModel * alloyList,double a_base , QWidget * parent) :
    QDialog(parent){

    setModal(true);

    m_list = alloyList;
    m_item = item;
    m_a = a_base;

    const Layer & cm = item->data(Qt::UserRole).value<Layer>();

    name_LE = new QLineEdit(cm.name);
    x_LE = new QLineEdit(QString::number(cm.x));
    d_LE = new QLineEdit(QString::number(cm.d));

    alloysCB = new QComboBox();
    alloysCB->setModel(m_list);
    alloysCB->setCurrentIndex(cm.alloyIndex.row());

    QFormLayout* form_layout = new QFormLayout();

    form_layout->addRow("Nazwa", name_LE);
    form_layout->addRow("Związek", alloysCB);
    form_layout->addRow("Zawartość x", x_LE);
    form_layout->addRow("Grubość warswy d", d_LE);

    execute_button = new QPushButton("Ok");
    cancel_button = new QPushButton("Anuluj");

    QVBoxLayout * main_layout = new QVBoxLayout();
    main_layout->addLayout(form_layout);
    QHBoxLayout * h_layout = new QHBoxLayout();
    h_layout->addWidget(execute_button);
    h_layout->addWidget(cancel_button);
    main_layout->addLayout(h_layout);

    this->setLayout(main_layout);

    connect(execute_button, SIGNAL(clicked()), this, SLOT(populate()));
    connect(cancel_button, SIGNAL(clicked()), this, SLOT(reject()));



}

void LayerPropertiesDialog::populate(){

    bool succes_x, succes_d, succes_aCB;

    Layer temp_layer;

    temp_layer.name = name_LE->text();
    temp_layer.x = x_LE->text().toDouble(&succes_x);
    temp_layer.d = d_LE->text().toDouble(&succes_d);
    temp_layer.a_base = m_a;

    if(succes_x){
        if ((temp_layer.x > 1.0 )|| (temp_layer.x < 0)){
            succes_x = false;
        }
    }
    if(succes_d){
        if ((temp_layer.d <= 0.0 )){
            succes_d = false;
        }
    }

    if ( alloysCB->currentIndex() != -1){
        temp_layer.alloyIndex = m_list->index(alloysCB->currentIndex(), 0);
        succes_aCB = true;
    } else {
        succes_aCB = false;
    }


    if (succes_x && succes_d && succes_aCB) {

        QVariant v;
        v.setValue(temp_layer);

        m_item->setData(Qt::DisplayRole, name_LE->text());
        m_item->setData(Qt::UserRole, v);

        this->accept();
    } else {
        QString str;
        str = "Niepoprawne dane dla: \n";
        if(!succes_x)
            str += "x - wpisz wartość z przedziału <0,1> \n";
        if(!succes_d)
            str += "d - wpisz wartość większą od zera \n";
        if(!succes_aCB)
            str += "Związku \n";
        QMessageBox::critical(this,"Blad",str);
    }
}
